import { useCallback, useRef } from "react"
import { Dialog, DialogTitle, DialogContent, DialogActions } from "@mui/material"
import { useTranslation } from "react-i18next"
import { Formik,Form, Field, ErrorMessage } from "formik"
import ButtonStyled from './ButtonStyled'
import MyTextField from '../../MyForm/modules/MyTextField'

const MuiLangEditDialog = (props) => {
  const { t } = useTranslation()
  const { open, handleClose, initialI18n, confirm, required } = props

  const formRef = useRef(null)

  const submitForm = useCallback((values) => {
    confirm(values)
    handleClose()
  }, [confirm, handleClose])

  const formValidate = useCallback((values) => {
    const errors = {}
    if (!values.defaultValue && required) {
      errors.defaultValue = t('common.defaultValueEmpty')
    }
    return errors
  }, [t, required])

  const dialogClose = useCallback((event, reason) => {
    if (reason === 'backdropClick') return
    handleClose()
  }, [handleClose])

 return (
  <div>
    <Dialog open={open} onClose={dialogClose}>
      <Formik initialValues={initialI18n} innerRef={formRef} onSubmit={submitForm} validate={(values) => formValidate(values)}>
        {() => (
          <Form className="rowForm" noValidate>
            <DialogTitle>
              {t('common.internationalConfig')}
            </DialogTitle>
            <DialogContent dividers style={{ width: '443px' }}>
              <div className="formItem">
                <Field required={required} style={{width: '100%'}} name="defaultValue" label={t('common.default')} component={MyTextField} />
                <ErrorMessage name="defaultValue" component="div" className="errorsMsgComp" />
              </div>
              <div className="formItem">
                <Field style={{width: '100%'}} name="i18nValue.zh_CN" label='简体中文' component={MyTextField} />
                <ErrorMessage name="i18nValue.zh_CN" component="div" className="errorsMsgComp" />
              </div>
              <div className="formItem">
                <Field style={{width: '100%'}} name="i18nValue.en_US" label='English' component={MyTextField} />
                <ErrorMessage name="i18nValue.en_US" component="div" className="errorsMsgComp" />
              </div>
            </DialogContent>
            <DialogActions>
              <ButtonStyled onClick={dialogClose}>{t('common.cancel')}</ButtonStyled>
              <ButtonStyled variant="contained" type='submit'>{t('common.confirm')}</ButtonStyled>
            </DialogActions>
          </Form>
        )}
      </Formik>
    </Dialog>
  </div>
 )
}

export default MuiLangEditDialog